<?php

namespace App\Utils;

use Illuminate\Support\Facades\Log;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class ReqResLogger
{
    /**
     * @param $message
     * @param array $data
     * @param string $filename
     * @param string $type
     * @return void
     */
    private static function _save($message, array $data = [], string $filename = 'log', string $type = 'info'): void
    {
        try {
            $dir_name = $filename;
            $log = new Logger('req_res');
            if (PHP_SAPI == 'cli') {
                // 命令行访问脚本的，加一个cli标识和用户浏览器访问的区分开
                $filename .= '_cli';
            }
            $filename = date('Y-m-d') . '-' . $filename . '.log';
            $path = storage_path('logs/' . $dir_name);
            // 有时候运维没给号权限，容易导致写入日志失败
            self::mkDirs($path);
            $path = $path . '/' . $filename;
            if (gettype($data) != 'array') {
                $message .= "：" . json_encode($data);
                $data = [];
            }
            if ($type == 'info') {
                $log->pushHandler(new StreamHandler($path, Logger::INFO));
            } else {
                $log->pushHandler(new StreamHandler($path, Logger::ERROR));
            }
            $log->info($message, $data);
        } catch (\Exception $e) {
            Log::info("日志记录错误:" . $e->getMessage());
        }
    }

    /**
     * @param $message
     * @param array $data
     * @param string $filename
     * @return void
     */
    public static function info($message, array $data = [], string $filename = 'info'): void
    {
        self::_save($message, $data, $filename);
    }

    /**
     * 单文件记录错误日志
     * @param $message
     * @param array $data
     * @param string $filename
     * @return void
     */
    public static function error($message, array $data = [], string $filename = 'error'): void
    {
        self::_save($message, $data, $filename);
    }

    /**
     * 给日志文件夹权限
     * @param $dir
     * @param int $mode
     * @return bool
     */
    public static function mkDirs($dir, int $mode = 0777): bool
    {
        if (is_dir($dir) || @mkdir($dir, $mode))
            return TRUE;
        if (!self::mkdirs(dirname($dir), $mode))
            return FALSE;
        return @mkdir($dir, $mode);
    }
}
